#include "ViewerWidgetWrapper.h"

// 导入Qt相关头文件
#pragma push_macro("slots")
#pragma push_macro("signals")
#undef slots
#undef signals
#include <QWidget>
#include <odv/odvGUI/ViewerWidget.h>
#pragma pop_macro("slots")
#pragma pop_macro("signals")
// 导入Qt相关头文件

// 用于将 QWidget* 转换为 Python 对象的辅助函数
pybind11::object convertQWidgetToPython(QWidget* widget) {
    if (!widget) return pybind11::none();

    // 获取 shiboken2 的 wrapInstance 函数
    auto shiboken = pybind11::module_::import("shiboken2");
    auto wrapInstance = shiboken.attr("wrapInstance");

    // 将指针地址转换为 Python 整数
    auto ptr = reinterpret_cast<std::uintptr_t>(widget);

    // 调用 shiboken2.wrapInstance
    return wrapInstance(ptr, pybind11::module_::import("PySide2.QtWidgets").attr("QWidget"));
}

void bind_ViewerWidget(py::module_& m) {

    py::class_<QWidget>(m, "QWidget");

    py::class_<odv::ViewerWidget, std::shared_ptr<odv::ViewerWidget>>(m, "ViewerWidget")
        .def(py::init<odv::CoordinateSystem, odv::MapProjection>(),
             py::arg("cs") = odv::CoordinateSystem::Projected,
             py::arg("mp") = odv::MapProjection::EquidistantCylindrical)
        .def("getViewer", &odv::ViewerWidget::getViewer)
        //.def("getQtWidget", &odv::ViewerWidget::getQtWidget, py::return_value_policy::reference)
        .def("getQtWidget", [](odv::ViewerWidget& self) {
            QWidget* widget = self.getQtWidget();
            return convertQWidgetToPython(widget);
        });
}
